#include "compile_run.hpp"
#include "../comm/httplib.h"
#include <string>
#include <iostream>
#include <jsoncpp/json/json.h>

using namespace ns_compile_and_run;
using namespace httplib;

void MyDaemon()
{
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
    if(fork() > 0) exit(0);
    setsid();
    int fd = open("/dev/null", O_RDWR);
    if(fd > 0)
    {
        dup2(0, fd);
        dup2(1, fd);
        dup2(2, fd);
        close(fd);
    }
}

void Usage(const std::string &command)
{
    std::cout << "Usage: " << command << " port" << std::endl;
}
// 编译服务随时可能被多个人请求，必须保证传递上来的code，形成源文件名称的时候，要具有
// 唯一性，要不然多个用户之间会互相影响
//./compile_server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }
    MyDaemon(); // 守护进程；
    Server svr;
    svr.Post("/compile_and_run", [](const Request &req, Response &res){
        // 用户请求的服务正文是我们想要的json string
        std::string in_json = req.body;
        std::string out_json;
        if(!in_json.empty())
        {
            CompileAndRun::start(in_json, &out_json);
            res.set_content(out_json, "application/json;charset=utf-8");
        } 
    });
    svr.listen("0.0.0.0", atoi(argv[1])); // 启动http服务

    return 0;
}   